﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using DataBaseTable;
public partial class Login_M : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Form.DefaultButton = "ctl00$ContentPlaceHolder1$Lg";  
    }
    protected void Lg_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.User_Name.Text.Trim()) || string.IsNullOrEmpty(this.User_Password.Text.Trim()))
        {
            ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('用户名和密码不能为空');</script>");
            return;
        }
        string UserRole = string.Empty; ;
        if (CheckAdmin(ref UserRole))
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.User_Name.Text, DateTime.Now, DateTime.Now.AddMinutes(30), true, UserRole.Trim(), FormsAuthentication.FormsCookiePath);
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
            if (ticket.IsPersistent)
                cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = FormsAuthentication.DefaultUrl;
            }
            Response.Redirect(returnUrl);
        }
        else
        {
            ClientScript.RegisterStartupScript(GetType(), "message", "<script>alert('用户名或密码错误');</script>");
        }
    }
    private bool CheckAdmin(ref string UserRole)
    {
        AdminTable newuser = new AdminTable(this.User_Name.Text.Trim());
        string password = FormsAuthentication.HashPasswordForStoringInConfigFile(this.User_Password.Text.Trim(), "MD5").ToLower();
        if (newuser.ID != 0 && newuser.UserPassword == password)
        {
            UserRole = newuser.UserRole;
            return true;
        }
        else
        {
            return false;
        }

    }
}